import React, { Component } from 'react';
import styles from './index.less';
import { Button, Card, Col, Input, Popconfirm, Radio, Row, Select } from 'antd';
import styled from 'styled-components';
import StandardTable from '@/components/StandardTable';
import CreateView from '@/pages/Company/List/Create';
import { connect } from 'dva';
import BaseComponent from '@/components/BaseComponent';
import LocationSelect from '@/pages/Company/List/LocationSelect';
import BusinessCodeSelect from '@/pages/Company/List/BusinessCodeSelect';
import PreviewView from '@/pages/Company/List/Preview';
import EditView from '@/pages/Company/List/Edit';

const { Option } = Select;

/**
 * 顶部右侧相关信息
 * @type {StyledComponent<"div", AnyIfEmpty<DefaultTheme>, {}, never>}
 */
const HeaderRight = styled.div`
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
`;

const MBtn = styled.a`
  color: #40a9ff;
  margin-left: 8px;
  margin-right: 8px;
`;

/**
 * 企业信息管理
 */
@connect(({ companyinfo, loading }) => ({
  data: companyinfo.data,
  isLoading: loading.effects['companyinfo/listAllCompanyInfos'],
  isCreating: loading.effects['companyinfo/createNewCompany'],
  isUpdating: loading.effects['companyinfo/updateCompanyInfo'],
  isDeling: loading.effects['companyinfo/delCompanyInfo'],
}))
class CompanyList extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      // 企业类型
      companyType: [],
      // 企业名称
      keyword: '',
      // 被选中的rows
      selectedRowKeys: [],
      // 新增
      createVisible: false,
      // 预览
      previewVisible: false,
      // 编辑
      updateVisible: false,
      // 区域列表
      areaOptions: [],
      // 地址选择可见性
      locationSelectVisible: false,
      // 选择行业代码对话框visible
      businessSelectVisible: false,
      // 待预览或编辑的企业数据
      record: {},
    };
  }

  columns = [
    {
      title: '企业名称',
      key: 'col1',
      width: 200,
      dataIndex: 'company_name',
    },
    {
      title: '法人代表',
      key: 'col2',
      width: 100,
      dataIndex: 'legal_person',
    },
    {
      title: '营业执照',
      key: 'col3',
      width: 160,
      dataIndex: 'business_license',
      render: (text, record, index) => {
        const { business_license } = record;
        if (business_license && business_license != '') {
          return (
            <img
              className={styles.mimage}
              src={record.business_license}
              onClick={this.handlePreviewImage}
            />
          );
        } else {
          return '未上传';
        }
      },
    },
    {
      title: '营业期限',
      key: 'col4',
      width: 130,
      dataIndex: 'business_term',
    },
    {
      title: '联系方式',
      key: 'col5',
      width: 130,
      dataIndex: 'contacts_mobile',
    },
    {
      title: '地址',
      key: 'col6',
      width: 160,
      dataIndex: 'company_address',
    },
    {
      title: '企业类型',
      key: 'col7',
      width: 160,
      dataIndex: 'company_type',
      render: (text, record, index) => {
        const { company_type } = record;
        if (company_type == 1) {
          return '固体废物产生源单位';
        } else if (company_type == 2) {
          return '危险废物运输单位';
        } else if (company_type == 3) {
          return '经营单位';
        }
      },
    },
    /*{
      title: '审核状态',
      key: 'col8',
      width: 100,
      dataIndex: 'audit_status',
    },*/
    {
      title: '操作',
      key: 'col9',
      width: 200,
      fixed: 'right',
      render: (text, record, index) => {
        return (
          <div className={styles.operate_col}>
            <MBtn
              onClick={() => {
                this.handlePreviewClick({ record });
              }}
            >
              详情
            </MBtn>
            <MBtn
              onClick={() => {
                this.handleEditClick({ record });
              }}
            >
              编辑
            </MBtn>
            <Popconfirm
              title="确定执行当前操作吗?"
              onConfirm={() => {
                this.handleDelClick({ record });
              }}
            >
              <MBtn>删除</MBtn>
            </Popconfirm>
          </div>
        );
      },
    },
  ];

  componentDidMount() {
    this.listAllCompanyInfos();
    this.listAllAnhuiRegions();
  }

  /**
   * 分页获取列表数据
   */
  listAllCompanyInfos = () => {
    this.listAllCompanyInfosBy({});
  };

  listAllCompanyInfosBy = params => {
    this.execHttp('companyinfo/listAllCompanyInfos', { currentPage: 1, pageSize: 10, ...params });
  };

  /**
   * 获取安徽省的行政区划
   */
  listAllAnhuiRegions = () => {
    this.execHttp('companyinfo/listAllAnhuiRegions', {})
      .then(value => {
        const { success, list } = value.data;
        if (success) {
          this.setState({ areaOptions: list });
        }
      })
      .catch(reason => {});
  };

  /**
   * 执行删除任务
   * @param id
   */
  delCompanyInfo = ({ id }) => {
    if (this.props.isDeling) {
      return;
    }
    const hide = this.loadingMessage('操作中,请稍后...');
    this.execHttp('companyinfo/delCompanyInfo', { id: id })
      .then(value => {
        hide();
        const {
          success,
          data: { msg },
        } = value;
        if (success) {
          this.successMessage(msg);
        } else {
          this.errorMessage(msg);
        }
        this.listAllCompanyInfos();
      })
      .catch(reason => {
        hide();
        this.errorMessage(reason);
      });
  };

  render() {
    const { selectedRowKeys } = this.state;
    return (
      <div>
        <Card bordered={true} title={'企业信息管理'}>
          <Row>
            <Col span={8}>
              <Button
                type="primary"
                style={{ marginRight: '8px' }}
                onClick={this.handleShowCreateClick}
              >
                新建
              </Button>
            </Col>
            <Col span={16}>
              <HeaderRight>
                <Select
                  placeholder={'请选择企业类型'}
                  style={{ width: '200px', marginRight: '8px' }}
                  allowClear
                  value={this.state.companyType}
                  onChange={this.handleCompanyTypeChange}
                >
                  <Option value="1">固体废物产生源单位</Option>
                  <Option value="2">危险废物运输单位</Option>
                  <Option value="3">经营单位</Option>
                </Select>
                <Input
                  value={this.state.keyword}
                  style={{ width: '200px', marginRight: '8px' }}
                  placeholder="请输入企业名称"
                  allowClear
                  onChange={this.handleKeywordChange}
                />
                <Button
                  type="primary"
                  style={{ marginRight: '8px' }}
                  onClick={this.handleSearchClick}
                >
                  搜索
                </Button>
                <Button type="default" onClick={this.handleResetClick}>
                  重置
                </Button>
              </HeaderRight>
            </Col>
          </Row>
        </Card>
        {/*列表*/}
        <Card bordered={true} style={{ marginTop: '16px' }}>
          <StandardTable
            data={this.props.data}
            hasSelection={false}
            selectedRows={selectedRowKeys}
            columns={this.columns}
            rowKey={'id'}
            loading={this.props.isLoading}
            onChange={this.handleTableChange}
            scroll={{ x: true }}
          />
        </Card>
        {/*新增*/}
        {this.state.createVisible ? (
          <CreateView
            wrappedComponentRef={createView => (this.createView = createView)}
            visible={this.state.createVisible}
            areaOptions={this.state.areaOptions}
            onClose={this.handleCreateViewClose}
            onConfirmClick={this.handleCreateViewConfirmClick}
            onSelectLocationClick={this.handleOnSelectLocationClick}
            onSelectBusinessCodeClick={this.handleOnSelectBusinessCodeClick}
          ></CreateView>
        ) : null}
        {/*编辑*/}
        {this.state.updateVisible && Object.keys(this.state.record).length > 0 ? (
          <EditView
            wrappedComponentRef={createView => (this.updateView = createView)}
            visible={this.state.updateVisible}
            areaOptions={this.state.areaOptions}
            record={this.state.record}
            onClose={this.handleUpdateViewClose}
            onConfirmClick={this.handleUpdateViewConfirmClick}
            onSelectLocationClick={this.handleOnSelectLocationClick}
            onSelectBusinessCodeClick={this.handleOnSelectBusinessCodeClick}
          ></EditView>
        ) : null}
        {/*预览*/}
        {this.state.previewVisible && Object.keys(this.state.record).length > 0 ? (
          <PreviewView
            visible={this.state.previewVisible}
            onClose={() => {
              this.setState({ previewVisible: false });
            }}
            record={this.state.record}
          ></PreviewView>
        ) : null}
        {/*地址选择*/}
        {this.state.locationSelectVisible ? (
          <LocationSelect
            visible={this.state.locationSelectVisible}
            onSubmitClick={this.handleOnLocationSelectSubmitClick}
            onCancel={() => {
              this.setState({ locationSelectVisible: false });
            }}
          ></LocationSelect>
        ) : null}
        {/*行业代码选择*/}
        {this.state.businessSelectVisible ? (
          <BusinessCodeSelect
            visible={this.state.businessSelectVisible}
            onCancel={() => {
              this.setState({ businessSelectVisible: false });
            }}
            onOkClick={this.handleBusinessCodeSelectOkClick}
          ></BusinessCodeSelect>
        ) : null}
      </div>
    );
  }

  /**
   * 行业代码选择ok
   * @param data
   */
  handleBusinessCodeSelectOkClick = data => {
    const { title, key } = data;
    const { createVisible, updateVisible } = this.state;
    if (createVisible) {
      this.createView.setBusinessCode({ code: `${key}|${title}` });
    } else if (updateVisible) {
      this.updateView.setBusinessCode({ code: `${key}|${title}` });
    }

    this.setState({ businessSelectVisible: false });
  };
  /**
   * 企业类型改变
   * @param value
   */
  handleCompanyTypeChange = value => {
    this.setState({ companyType: value });
  };

  /**
   *搜索按钮被点击
   */
  handleSearchClick = () => {
    const { keyword, companyType } = this.state;
    this.listAllCompanyInfosBy({ keyword: keyword, companyType: companyType });
  };

  /**
   * 关键字改变
   * @param e
   */
  handleKeywordChange = e => {
    const {
      target: { value },
    } = e;
    this.setState({
      keyword: value,
    });
  };

  /**
   * 重置按钮被点击
   */
  handleResetClick = () => {
    this.setState({ keyword: '', companyType: [] }, () => {
      this.listAllCompanyInfosBy({});
    });
  };

  /**
   * table状态改变时调用
   * @param pagination
   * @param filtersArg
   * @param sorter
   */
  handleTableChange = (pagination, filtersArg, sorter) => {
    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    this.listAllCompanyInfosBy(params);
  };

  /**
   * table的checkbox状态改变后调用
   * @param {*} selectedRowKeys
   */
  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };

  /**
   * 新建按钮被点击
   */
  handleShowCreateClick = () => {
    console.log('新建按钮被点击');
    this.setState({
      createVisible: true,
    });
  };

  /**
   *新增关闭按钮被点击
   */
  handleCreateViewClose = e => {
    this.setState({
      createVisible: false,
    });
  };

  /**
   * 新增视图确认按钮被点击
   * @param data
   */
  handleCreateViewConfirmClick = ({ data }) => {
    if (this.props.isCreating) {
      return;
    }
    const hide = this.loadingMessage('操作中,请稍后...');
    this.execHttp('companyinfo/createNewCompany', { ...data })
      .then(value => {
        hide();
        const {
          success,
          data: { msg },
        } = value;
        if (success) {
          this.successMessage(msg);
        } else {
          this.errorMessage('出错了');
        }
        this.setState({ createVisible: false }, () => {
          this.listAllCompanyInfos();
        });
      })
      .catch(reason => {
        hide();
        this.errorMessage(reason);
      });
  };

  /**
   * 处理点击事件
   */
  handleOnSelectLocationClick = () => {
    this.setState({ locationSelectVisible: true });
  };

  /**
   * 处理点击事件
   */
  handleOnSelectBusinessCodeClick = () => {
    this.setState({ businessSelectVisible: true });
  };

  handleOnLocationSelectSubmitClick = ({ lng, lat }) => {
    const { createVisible, updateVisible } = this.state;
    if (createVisible) {
      this.createView.setLngLat({
        lng,
        lat,
      });
    } else if (updateVisible) {
      this.updateView.setLngLat({
        lng,
        lat,
      });
    }

    this.setState({ locationSelectVisible: false });
  };

  /**
   * 删除按钮被点击
   * @param record
   */
  handleDelClick = ({ record }) => {
    this.delCompanyInfo({ id: record.id });
  };

  /**
   * 预览按钮被点击
   * @param record
   */
  handlePreviewClick = ({ record }) => {
    this.setState({
      record: record,
      previewVisible: true,
    });
  };

  /**
   * 编辑按钮被点击
   * @param record
   */
  handleEditClick = ({ record }) => {
    this.setState({
      record: record,
      updateVisible: true,
    });
  };

  /**
   *编辑关闭按钮被点击
   */
  handleUpdateViewClose = e => {
    this.setState({
      createVisible: false,
    });
  };

  /**
   * 编辑视图确认按钮被点击
   * @param data
   */
  handleUpdateViewConfirmClick = ({ data }) => {
    if (this.props.isUpdating) {
      return;
    }
    const hide = this.loadingMessage('操作中,请稍后...');
    this.execHttp('companyinfo/updateCompanyInfo', { ...data })
      .then(value => {
        hide();
        const {
          success,
          data: { msg },
        } = value;
        if (success) {
          this.successMessage(msg);
        } else {
          this.errorMessage(msg);
        }
        this.setState({ updateVisible: false }, () => {
          this.listAllCompanyInfos();
        });
      })
      .catch(reason => {
        hide();
        this.errorMessage(reason);
      });
  };
}

export default CompanyList;
